/*
 * @Copyright: 2023 - 2023 www.hoperun.com Inc. All rights reserved.
 */

package com.lifeservice.task;

import com.lifeservice.common.utils.StringUtils;
import com.lifeservice.console.domain.LifeOrder;
import com.lifeservice.console.domain.LifeSupplierInfo;
import com.lifeservice.console.mapper.LifeOrderMapper;
import com.lifeservice.console.mapper.LifeSupplierInfoMapper;
import com.lifeservice.util.LifeServiceConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liu_yifeng
 * @function calculate score
 * @date 2023/3/8 14:32
 */
@Component("calculateScoreJob")
@Slf4j
public class CalculateScoreJob {
    @Autowired
    private LifeOrderMapper lifeOrderMapper;
    @Autowired
    private LifeSupplierInfoMapper lifeSupplierInfoMapper;

    public void calStaffAndSupplierScore() {
        int count = lifeOrderMapper.deleteDirtyOrder();
        log.info("order without supplier size is {}", count);
        LifeOrder query = new LifeOrder();
        query.setStatus(LifeServiceConstants.ORDER_STATUS_COMPLETE);
        List<LifeOrder> lifeOrderList = lifeOrderMapper.selectLifeOrderList(new LifeOrder());

        if (StringUtils.isNotEmpty(lifeOrderList)) {
            List<LifeSupplierInfo> lifeSupplierInfoList = lifeSupplierInfoMapper.selectLifeSupplierInfoList(new LifeSupplierInfo());
            if (StringUtils.isEmpty(lifeSupplierInfoList)) {
                return;
            }
            Map<String, LifeSupplierInfo> supplierInfoMap = lifeSupplierInfoList.stream().collect(Collectors.toMap(LifeSupplierInfo::getId, LifeSupplierInfo -> LifeSupplierInfo));
            Map<String, List<LifeOrder>> orderListGroupBySupplierId = lifeOrderList.stream().collect(Collectors.groupingBy(LifeOrder::getSupplierId));
            orderListGroupBySupplierId.forEach((supplierId, orderList) -> {
                LifeSupplierInfo supplierInfo = supplierInfoMap.get(supplierId);
                BigDecimal totalScore = orderList.stream().map(LifeOrder::getScore).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal finalScore = totalScore.divide(new BigDecimal(orderList.size()), 1, BigDecimal.ROUND_HALF_UP);
                supplierInfo.setScore(finalScore);
                lifeSupplierInfoMapper.updateLifeSupplierInfo(supplierInfo);
            });
        }
    }
}
